package org.itboys.store.web;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Maps;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.store.dto.ProductDetail;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.store.cache.ProductDetailLoader;
import org.itboys.store.entity.CarItem;
import org.itboys.store.entity.Product;
import org.itboys.store.entity.ProductBrand;
import org.itboys.store.entity.ProductCategory;
import org.itboys.store.search.ProductSearchDoc;
import org.itboys.store.search.ProductSearchService;
import org.itboys.store.service.StoreProductBrandService;
import org.itboys.store.service.StoreProductCategoryService;
import org.itboys.store.service.StoreProductCategorySpecService;
import org.itboys.store.service.StoreProductService;
import org.itboys.store.service.StoreProductTextService;
import org.itboys.store.service.StoreShopProductCategoryService;
import org.itboys.solr.client.SolrClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * 商品
 * @author huml
 *
 */
@RestController
@RequestMapping("/store/product")
public class StoreProductController extends BaseController{

	@Resource(name = "storeProductDetailLoader")
	private ProductDetailLoader productDetailLoader;
	@Resource(name = "storeProductSolrClient")
	private SolrClient productSolrClient;

	@Autowired
	private StoreProductService storeProductService;
	@Autowired
	private ProductSearchService productSearchService;
	@Autowired
	private StoreProductCategoryService storeProductCategoryService;
	@Autowired
	private StoreProductBrandService storeProductBrandService;
	@Autowired
	private StoreProductTextService storeProductTextService;
	@Autowired
	private StoreShopProductCategoryService storeShopProductCategoryService;
	@Autowired
	private StoreProductCategorySpecService storeProductCategorySpecService;
	@RequestMapping("/category")
	public void category(HttpServletResponse response){
		try {
			/*ProductCategory parentCategory = new ProductCategory();
			parentCategory.setName("全部");
			storeProductCategoryService.save(parentCategory);*/

			Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
			param.put("type", Product.TYPE_HT);
			List<Product> list = storeProductService.list(param);
			for (Product product : list) {
				productSolrClient.deleteDocument(product.getId() + "");
//				productDetailLoader.clearCache(product.getId());
				ProductDetail detail = productDetailLoader.get(product.getId());
				ProductSearchDoc doc = new ProductSearchDoc();
				doc.setProductId(product.getId());
//                doc.setBrandId(detail.getBrandId());
				doc.setCategoryFullIdPath(detail.getCatId().toString());
				doc.setProductName(detail.getTitle() + ":::" + detail.getBrandName() + ":::" + detail.getCatName());
				doc.setPrice(detail.getRealPrice());
				doc.setSoldCount(detail.getSoldCount());
				doc.setReadCount(detail.getReadCount());
				doc.setType(Product.TYPE_HT);
				productSearchService.buildProductSearchIndex(doc);
				logger.info("*****success******" + product.getId());
			}
			//按照产品分类分组
			/*Map<String, List<Product>> map = list.stream().collect(Collectors.groupingBy(Product::getCategory));
			Iterator<String> ite = map.keySet().iterator();
			while (ite.hasNext()) {
				String category = ite.next();
				ProductCategory category1 = new ProductCategory();
				category1.setParentId(1L);
				category1.setName(category);
				storeProductCategoryService.save(category1);
				List<Product> products = map.get(category);
				for (Product product : products ) {
					product.setCatId(category1.getId());
				}
				storeProductService.batchUpdate(products);
				for (Product product : products) {
					productSolrClient.deleteDocument(product.getId() + "");
					productDetailLoader.clearCache(product.getId());
					ProductDetail detail = productDetailLoader.get(product.getId());
					ProductSearchDoc doc = new ProductSearchDoc();
					doc.setProductId(product.getId());
//                doc.setBrandId(detail.getBrandId());
                    doc.setCategoryFullIdPath(detail.getCatId().toString());
					doc.setProductName(detail.getTitle() + ":::" + detail.getBrandName() + ":::" + detail.getCatName());
					doc.setPrice(detail.getRealPrice());
					doc.setSoldCount(detail.getSoldCount());
					doc.setReadCount(detail.getReadCount());
					doc.setType(Product.TYPE_HT);
					productSearchService.buildProductSearchIndex(doc);
				}
				logger.info("*****success******" + category);
			}*/
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 跳到商品管理页面
	 * @return
	 */
	@RequestMapping("/toListVM")
	public ModelAndView toListVM(@RequestParam("type")Integer type,Model model) {
		model.addAttribute("type", type);
		if(type.equals(Product.TYPE_HT)){
			return new ModelAndView("/ace/store/productList");
		} else {
			return new ModelAndView("/ace/store/productList1");
		}
	}

	/**
	 * 产品列表
	 * @param request
	 * @param response
     */
	@RequestMapping("/list")
	public void list(HttpServletRequest request, HttpServletResponse response){
		Page<Product> page = storeProductService.pageQuery(request);
		JsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}

	/**
	 * 跳转编辑页面
	 * @param id
	 * @param model
     * @return
     */
	@RequestMapping("/input")
	public ModelAndView input(@RequestParam("id") Long id,
					  Model model){
		Integer type = 2;
		if(id != null){
			ProductDetail detail = productDetailLoader.get(id);
			type = detail.getType();
			model.addAttribute("product", detail);
		}
		List<ProductBrand> pbs = storeProductBrandService.list(Maps.newHashMapWithExpectedSize(0));
		model.addAttribute("pbs", pbs);
		if(type.equals(Product.TYPE_HT)){
			return new ModelAndView("/ace/store/productInput");
		} else {
			return new ModelAndView("/ace/store/productInput1");
		}
	}

	/**
	 *
	 * @param product
	 * @param imgFile
	 * @param imgFiles
	 * @param request
     * @param response
     */
	@RequestMapping("/save")
	public void save(@ModelAttribute Product product,
					 @RequestParam(value="imgFile", required = false) MultipartFile imgFile,
					 @RequestParam(value="imgFiles", required = false) MultipartFile[] imgFiles,
					 HttpServletRequest request,HttpServletResponse response){
		try {
			storeProductService.insert(product, imgFile, imgFiles);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("/store/product/insert error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 修改产品信息   这里只能修改平台的产品分类和售价   不能更改海仓同步过来的信息
	 * @param id
	 * @param catId
	 * @param realPrice
	 * @param response
     */
	@RequestMapping("/update")
	public void update(@RequestParam("id")final Long id,
					   @RequestParam(value = "catId", required = false)Long catId,
					   @RequestParam(value = "brandId", required = false)Long brandId,
					   @RequestParam("marketPrice")Double marketPrice,
					   @RequestParam("realPrice")Double realPrice,
					   @RequestParam("pricePinkage")Integer pricePinkage,
					   @RequestParam("numPinkage")Integer numPinkage,
					   @RequestParam("postage")Integer postage,
					   @RequestParam(value = "scale", required = false)Double scale,
					   @RequestParam(value = "isHot", required = false)boolean isHot,
					   @RequestParam(value = "isRecommend", required = false)boolean isRecommend,
					   @RequestParam(value = "isSpecial", required = false)boolean isSpecial,
					   @RequestParam(value = "isGood", required = false)boolean isGood,
					   @RequestParam(value = "isLimit", required = false)boolean isLimit,
					   @RequestParam(value = "limitStartTime", required = false)Date limitStartTime,
					   @RequestParam(value = "limitEndDate", required = false)Date limitEndDate,
					   HttpServletResponse response){
		try {
			Product product = storeProductService.getById(id);
			product.setCatId(catId);
			product.setBrandId(brandId);
			product.setRealPrice(realPrice);
			product.setHot(isHot);
			product.setRecommend(isRecommend);
			product.setSpecial(isSpecial);
			product.setGood(isGood);
			product.setLimit(isLimit);
			product.setMarketPrice(marketPrice);
			product.setScale(scale == null ? 0d : scale);
			product.setPricePinkage(pricePinkage);
			product.setNumPinkage(numPinkage);
			product.setPostage(postage);
			if(isLimit && (limitStartTime == null || limitEndDate == null)){//选择了限时购但没有填写限时购的时间
				AjaxUtils.renderText(response, "1");
				return;
			}
			product.setLimitStartTime(limitStartTime);
			product.setLimitEndDate(limitEndDate);
			storeProductService.update(product);
			productDetailLoader.clearCache(id);
			ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();//开启线程  往搜索引擎里加信息
			fixedThreadPool.execute(new Runnable(){
				@Override
				public void run() {
					try {
						productSolrClient.deleteDocument(id.toString());
						ProductDetail detail = productDetailLoader.get(id);
						ProductSearchDoc doc = new ProductSearchDoc();
						doc.setProductId(id);
						doc.setBrandId(detail.getBrandId());
						doc.setCategoryFullIdPath(detail.getCatId().toString());
						doc.setProductName(detail.getTitle() + ":::" + detail.getBrandName() + ":::" + detail.getCatName());
						doc.setPrice(detail.getRealPrice());
						doc.setSoldCount(detail.getSoldCount());
						doc.setReadCount(detail.getReadCount());
						doc.setType(detail.getType());
						productSearchService.buildProductSearchIndex(doc);
					} catch (Exception e) {
						logger.error("publishSupplyPush error", e);
					}
				}
			});
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("/store/product/update error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 产品上下架
	 * @param id
	 * @param response
     */
	@RequestMapping("/upAndDownProduct")
	public void upAndDownProduct(@RequestParam("id")Long id,
								 HttpServletResponse response){
		try {
			Product product = storeProductService.getById(id);
			if(product.isUnShelve()){
				product.setUnShelve(false);
			} else {
				product.setUnShelve(true);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("/store/product/upAndDownProduct error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 删除
	 * @param id
	 * @param response
     */
	@RequestMapping("/delete")
	public void delete(@RequestParam("id")Long id,
					   HttpServletResponse response){
		try {
			storeProductService.delete(id);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("/store/product/delete error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

}
